#!/usr/bin/env python
"""
创建示例数据库实例的脚本
用于测试SQL查询功能
"""

import os
import sys
import django

# 设置Django环境
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'devops_platform.settings')
django.setup()

from sql_management.models import DatabaseInstance

def create_sample_instances():
    """创建示例数据库实例"""
    
    # 清除现有的示例数据
    DatabaseInstance.objects.filter(name__startswith='示例').delete()
    
    sample_instances = [
        {
            'name': 'DevOps平台MySQL数据库',
            'host': 'localhost',
            'port': 3306,
            'database_type': 'mysql',
            'username': 'devops_user',
            'password': 'devops_password123',
            'database_name': 'devops_platform',
            'description': 'DevOps平台主数据库实例'
        },
        {
            'name': '示例MySQL测试库',
            'host': 'localhost',
            'port': 3306,
            'database_type': 'mysql',
            'username': 'devops_user',
            'password': 'devops_password123',
            'database_name': 'mysql',
            'description': 'MySQL系统数据库（用于查看系统表）'
        }
    ]
    
    created_instances = []
    
    for instance_data in sample_instances:
        try:
            instance = DatabaseInstance.objects.create(**instance_data)
            created_instances.append(instance)
            print(f"✅ 创建数据库实例: {instance.name}")
        except Exception as e:
            print(f"❌ 创建数据库实例失败: {instance_data['name']}, 错误: {e}")
    
    return created_instances

def test_connections():
    """测试数据库连接"""
    from sql_management.database_manager import DatabaseManager
    
    instances = DatabaseInstance.objects.filter(name__startswith='示例')
    
    print("\n🔍 测试数据库连接:")
    for instance in instances:
        try:
            result = DatabaseManager.test_connection(instance)
            if result['success']:
                print(f"✅ {instance.name}: 连接成功 ({result['connection_time']}s)")
            else:
                print(f"❌ {instance.name}: 连接失败 - {result['message']}")
        except Exception as e:
            print(f"❌ {instance.name}: 连接测试异常 - {e}")

def main():
    print("🚀 开始创建示例数据库实例...")
    
    # 创建示例实例
    instances = create_sample_instances()
    
    if instances:
        print(f"\n✅ 成功创建 {len(instances)} 个示例数据库实例")
        
        # 测试连接
        test_connections()
        
        print("\n📋 创建的数据库实例:")
        for instance in instances:
            print(f"  - {instance.name} ({instance.database_type})")
            print(f"    连接: {instance.host}:{instance.port}/{instance.database_name}")
            print(f"    描述: {instance.description}")
            print()
        
        print("🎯 现在可以在以下页面测试SQL查询功能:")
        print("  - 数据库实例管理: http://localhost:8080/cmdb/database-instances")
        print("  - SQL查询页面: http://localhost:8080/sql/query")
        
    else:
        print("❌ 没有创建任何数据库实例")

if __name__ == '__main__':
    main()
